class draw {

  // 点、线、面
  factor() {
    Cesium.tileSize = 256

    var viewer = new Cesium.Viewer('cesiumContainer', {
      selectionIndicator: false, // 是否获取选择周指示器
      useBrowserRecommendedResolution: false, // 是否以浏览器建议的分辨率渲染
      animation: false, // 是否显示动画控件
      baseLayerPicker: false, // 是否显示图层选择控件
      geocoder: false, // 是否显示地名查找控件
      timeline: false, // 是否显示时间线控件
      sceneModePicker: true, // 是否显示投影方式控件
      navigationHelpButton: false, // 是否显示帮助信息控件
      infoBox: false, // 是否显示点击要素之后显示的信息
    })
    viewer.scene.globe.preloadAncestors = false
    viewer.scene.primitives.destroyPrimitives = false
    viewer.scene.globe.depthTesAgainstTerrain = false
    var imageryLayers = viewer.imageryLayers
    Cesium.viewer = viewer

    // 天地图影像
    var tiandituImageLayer = new Cesium.ImageryLayer(
      // 描述初始化选项
      new Cesium.WebMapTileServiceImageryProvider({
        url: 'http://{s}.tianditu.gov.cn/img_w/wmts?service=wmts&request=GetTile&version=1.0.0' + '&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}' + '&style=default&format=tiles&tk=32242308ce844a52006d05b93404716f',
        layer: 'tdtImg_c',
        style: 'default',
        format: 'tiles',
        tileMatrixSetID: 'c',
        subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
        tilingScheme: new Cesium.WebMercatorTilingScheme(),
        tileMatrixLabels: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19'],
        maximumLevel: 20,
      })
    )
    viewer.imageryLayers.add(tiandituImageLayer)

    // 创建点
    var point = [
      {
        id: 'document',
        name: 'CZML Point',
        version: '1.0',
      },
      {
        id: 'point 1',
        name: 'point',
        position: {
          cartographicDegrees: [-111.0, 40.0, 0],
        },
        point: {
          color: {
            rgba: [255, 255, 255, 255],
          },
          outlineColor: {
            rgba: [255, 0, 0, 255],
          },
          outlineWidth: 4,
          pixelSize: 20,
        },
      },
    ]

    var dataSourcePromise = Cesium.CzmlDataSource.load(point)
    viewer.dataSources.add(dataSourcePromise)

    // 创建线
    viewer.scene.primitives.add(
      new Cesium.Primitive({
        geometryInstances: new Cesium.GeometryInstance({
          geometry: new Cesium.PolylineGeometry({
            positions: Cesium.Cartesian3.fromDegreesArray([-164.0, 40.0, -80.0, 40.0]),
            width: 5.0,
            vertexFormat: Cesium.PolylineColorAppearance.VERTEX_FORMAT,
          }),
          attributes: {
            color: Cesium.ColorGeometryInstanceAttribute.fromColor(new Cesium.Color(1.0, 0.0, 0.0, 0.8)),
          },
        }),
        appearance: new Cesium.PolylineColorAppearance(),
      })
    )

    // 创建面
    var surfaceArr = new Cesium.GeometryInstance({
      geometry: new Cesium.RectangleGeometry({
        rectangle: Cesium.Rectangle.fromDegrees(-140.0, 30.0, -120.0, 40.0),
        vertexFormat: Cesium.PerInstanceColorAppearance.VERTEX_FORMAT,
      }),
      attributes: {
        color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.fromRandom({ alpha: 0.7 })),
      },
    })

    viewer.scene.primitives.add(
      new Cesium.Primitive({
        geometryInstances: surfaceArr,
        appearance: new Cesium.PerInstanceColorAppearance(),
      })
    )
  }
  // 图形样式
  style() {
    Cesium.tileSize = 256

    var viewer = new Cesium.Viewer('cesiumContainer', {
      selectionIndicator: false, // 是否获取选择周指示器
      useBrowserRecommendedResolution: false, // 是否以浏览器建议的分辨率渲染
      animation: false, // 是否显示动画控件
      baseLayerPicker: false, // 是否显示图层选择控件
      geocoder: false, // 是否显示地名查找控件
      timeline: false, // 是否显示时间线控件
      sceneModePicker: true, // 是否显示投影方式控件
      navigationHelpButton: false, // 是否显示帮助信息控件
      infoBox: false, // 是否显示点击要素之后显示的信息
    })
    viewer.scene.globe.preloadAncestors = false
    viewer.scene.primitives.destroyPrimitives = false
    viewer.scene.globe.depthTesAgainstTerrain = false
    var imageryLayers = viewer.imageryLayers
    Cesium.viewer = viewer

    // 天地图影像
    var tiandituImageLayer = new Cesium.ImageryLayer(
      // 描述初始化选项
      new Cesium.WebMapTileServiceImageryProvider({
        url: 'http://{s}.tianditu.gov.cn/img_w/wmts?service=wmts&request=GetTile&version=1.0.0' + '&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}' + '&style=default&format=tiles&tk=32242308ce844a52006d05b93404716f',
        layer: 'tdtImg_c',
        style: 'default',
        format: 'tiles',
        tileMatrixSetID: 'c',
        subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
        tilingScheme: new Cesium.WebMercatorTilingScheme(),
        tileMatrixLabels: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19'],
        maximumLevel: 20,
      })
    )
    viewer.imageryLayers.add(tiandituImageLayer)

    // 以经纬度返回笛卡尔坐标
    var positionOnEllipsoid = Cesium.Cartesian3.fromDegrees(-90.0, 40.0)

    // 绘制椭圆
    var radii = new Cesium.Cartesian3(200000.0, 200000.0, 300000.0)
    var modelMatrix = Cesium.Matrix4.multiplyByTranslation(Cesium.Transforms.eastNorthUpToFixedFrame(positionOnEllipsoid), new Cesium.Cartesian3(0.0, 0.0, radii.z), new Cesium.Matrix4())
    var ellipsoidGeometry = new Cesium.EllipsoidGeometry({
      vertexFormat: Cesium.PerInstanceColorAppearance.VERTEX_FORMAT,
      radii: radii,
    })

    var ellipse = new Cesium.GeometryInstance({
      geometry: ellipsoidGeometry,
      modelMatrix: modelMatrix,
      attributes: {
        color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.RED),
      },
    })

    // 绘制圆柱体
    var length = 400000.0
    positionOnEllipsoid = Cesium.Cartesian3.fromDegrees(-120.0, 40.0)
    var modelMatrix = Cesium.Matrix4.multiplyByTranslation(Cesium.Transforms.eastNorthUpToFixedFrame(positionOnEllipsoid), new Cesium.Cartesian3(0.0, 0.0, length * 0.5), new Cesium.Matrix4())
    var cylinderGeometry = new Cesium.CylinderGeometry({
      length: length,
      topRadius: 200000.0,
      bottomRadius: 200000.0,
      vertexFormat: Cesium.PerInstanceColorAppearance.VERTEX_FORMAT,
    })

    var cylindrical = new Cesium.GeometryInstance({
      geometry: cylinderGeometry,
      modelMatrix: modelMatrix,
      attributes: {
        color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.YELLOW), // 颜色
      },
    })

    // 绘制圆锥
    positionOnEllipsoid = Cesium.Cartesian3.fromDegrees(-105.0, 40.0)
    modelMatrix = Cesium.Matrix4.multiplyByTranslation(Cesium.Transforms.eastNorthUpToFixedFrame(positionOnEllipsoid), new Cesium.Cartesian3(0.0, 0.0, length * 0.5), new Cesium.Matrix4())
    cylinderGeometry = new Cesium.CylinderGeometry({
      length: length,
      topRadius: 0.0,
      bottomRadius: 200000.0,
      vertexFormat: Cesium.PerInstanceColorAppearance.VERTEX_FORMAT,
    })

    var cone = new Cesium.GeometryInstance({
      geometry: cylinderGeometry,
      modelMatrix: modelMatrix,
      attributes: {
        color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.BLUE),
      },
    })

    // 添加图形到地图中
    viewer.scene.primitives.add(
      new Cesium.Primitive({
        geometryInstances: [ellipse, cylindrical, cone],
        appearance: new Cesium.PerInstanceColorAppearance({
          translucent: false,
          closed: true,
        }),
      })
    )

    var circleGeometry = new Cesium.CircleGeometry({
      center: Cesium.Cartesian3.fromDegrees(113.467112, 34.14874),
      radius: 1.0,
      vertexFormat: Cesium.PerInstanceColorAppearance.VERTEX_FORMAT,
    })

    var redCircleInstance = new Cesium.GeometryInstance({
      geometry: circleGeometry,
      attributes: {
        color: Cesium.ColorGeometryInstanceAttribute.fromColor(new Cesium.Color(1.0, 0.0, 0.0, 0.5)),
      },
    })
    // Add the geometry instance to primitives.
    viewer.scene.primitives.add(
      new Cesium.Primitive({
        geometryInstances: redCircleInstance,
        appearance: new Cesium.PerInstanceColorAppearance({
          closed: true,
        }),
      })
    )
  }

  // 图形编辑
  edit() {
    var activeShapePoints = [];
    var activeShape;
    var floatingPoint;

    Cesium.tileSize = 256
    Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI5MWVkMjllNy03ZjY4LTQ3YmQtOTgxOC05NGQ5YTU0ZjM5ZGEiLCJpZCI6MzU5Nywic2NvcGVzIjpbImFzciIsImdjIl0sImlhdCI6MTUzODE5MTUyM30.dtS2F3-q2fGoA93N7cFl-LCikK-Rjk7v01WWA-RqCxg'

    var viewer = new Cesium.Viewer('cesiumContainer', {
      selectionIndicator: false,
      useBrowserRecommendedResolution: false,
      animation: false, //是否显示动画控件
      baseLayerPicker: false, //是否显示图层选择控件
      geocoder: false, //是否显示地名查找控件
      timeline: false, //是否显示时间线控件
      sceneModePicker: true, //是否显示投影方式控件
      navigationHelpButton: false, //是否显示帮助信息控件
      infoBox: false, //是否显示点击要素之后显示的信息
      imageryProvider: false,
      fullscreenButton: true,
    })
    viewer.scene.globe.preloadAncestors = false
    viewer.scene.primitives.destroyPrimitives = false
    viewer.scene.globe.depthTestAgainstTerrain = true
    var imageryLayers = viewer.imageryLayers
    Cesium.viewer = viewer

    var scene = viewer.scene

    //天地图影像图层
    var tiandituImageLayer = new Cesium.ImageryLayer(
      new Cesium.WebMapTileServiceImageryProvider({
        url: 'http://{s}.tianditu.gov.cn/img_w/wmts?service=wmts&request=GetTile&version=1.0.0' + '&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}' + '&style=default&format=tiles&tk=440b96d736fad95da7934bc130a2258a',
        layer: 'tdtImg_c',
        style: 'default',
        format: 'tiles',
        tileMatrixSetID: 'c',
        subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
        tilingScheme: new Cesium.WebMercatorTilingScheme(),
        tileMatrixLabels: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19'],
        maximumLevel: 20,
      })
    )
    viewer.imageryLayers.add(tiandituImageLayer)

    viewer.scene.globe.depthTestAgainstTerrain = true;

    var handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);

    //双击鼠标左键清除默认事件
    viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
    //绘制点
    function createPoint(worldPosition) {
      var point = viewer.entities.add({
        position: worldPosition,
        point: {
          color: Cesium.Color.WHITE,
          pixelSize: 5,
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
        }
      });
      return point;
    }
    //初始化为线
    var drawingMode = 'line';

    $('.btnBox').on('click', 'button', function () {
      let text = $(this).text()
      if (text === '线') {
        console.log(text);
        drawingMode = 'line'
      } else if (text === '面') {
        console.log(text);
        drawingMode = 'polygon'
      } else if (text === '圆') {
        console.log(text);
        drawingMode = 'circle'
      } else if (text === '矩形') {
        console.log(text);
        drawingMode = 'rectangle'
      }
    })

    //绘制图形
    function drawShape(positionData) {
      var shape;
      if (drawingMode === 'line') {
        shape = viewer.entities.add({
          polyline: {
            positions: positionData,
            clampToGround: true,
            width: 3
          }
        });
      } else if (drawingMode === 'polygon') {
        shape = viewer.entities.add({
          polygon: {
            hierarchy: positionData,
            material: new Cesium.ColorMaterialProperty(Cesium.Color.WHITE.withAlpha(0.7))
          }
        });
      } else if (drawingMode === 'circle') {
        var value = typeof positionData.getValue === 'function' ? positionData.getValue(0) : positionData;
        shape = viewer.entities.add({
          position: activeShapePoints[0],
          name: 'Blue translucent, rotated, and extruded ellipse with outline',
          type: 'Selection tool',
          ellipse: {
            semiMinorAxis: new Cesium.CallbackProperty(function () {
              //半径 两点间距离
              var r = Math.sqrt(Math.pow(value[0].x - value[value.length - 1].x, 2) + Math
                .pow(value[0].y - value[value.length - 1].y, 2));
              return r ? r : r + 1;
            }, false),
            semiMajorAxis: new Cesium.CallbackProperty(function () {
              var r = Math.sqrt(Math.pow(value[0].x - value[value.length - 1].x, 2) + Math
                .pow(value[0].y - value[value.length - 1].y, 2));
              return r ? r : r + 1;
            }, false),
            material: Cesium.Color.BLUE.withAlpha(0.5),
            outline: true
          }
        });
      } else if (drawingMode === 'rectangle') {
        var arr = typeof positionData.getValue === 'function' ? positionData.getValue(0) : positionData;
        shape = viewer.entities.add({
          name: 'Blue translucent, rotated, and extruded ellipse with outline',
          rectangle: {
            coordinates: new Cesium.CallbackProperty(function () {
              var obj = Cesium.Rectangle.fromCartesianArray(arr);
              return obj;
            }, false),
            material: Cesium.Color.RED.withAlpha(0.5)
          }
        });
      }
      return shape;
    }
    //鼠标左键
    handler.setInputAction(function (event) {
      var earthPosition = viewer.scene.pickPosition(event.position);
      if (Cesium.defined(earthPosition)) {
        if (activeShapePoints.length === 0) {
          floatingPoint = createPoint(earthPosition);
          activeShapePoints.push(earthPosition);
          var dynamicPositions = new Cesium.CallbackProperty(function () {
            if (drawingMode === 'polygon') {
              return new Cesium.PolygonHierarchy(activeShapePoints);
            }
            return activeShapePoints;
          }, false);
          activeShape = drawShape(dynamicPositions);
        }
        activeShapePoints.push(earthPosition);
        createPoint(earthPosition);
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    //鼠标移动
    handler.setInputAction(function (event) {
      if (Cesium.defined(floatingPoint)) {
        var newPosition = viewer.scene.pickPosition(event.endPosition);
        if (Cesium.defined(newPosition)) {
          floatingPoint.position.setValue(newPosition);
          activeShapePoints.pop();
          activeShapePoints.push(newPosition);
        }
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    function terminateShape() {
      activeShapePoints.pop();
      if (activeShapePoints.length) {
        drawShape(activeShapePoints);
      }
      viewer.entities.remove(floatingPoint);
      viewer.entities.remove(activeShape);
      floatingPoint = undefined;
      activeShape = undefined;
      activeShapePoints = [];
    }

    handler.setInputAction(function (event) {
      terminateShape();
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
  }
}
